﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core.Models;
using BootstrapAdmin.Web.Core.Services;
using PetaPoco;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services;

internal sealed class CustomService : ICustomService
{
    private const string PLC_Sign_Card = nameof(PLC_Sign_Card); // 刷卡
    private const string PLC_Sign_SpotCheck = nameof(PLC_Sign_SpotCheck); // 点检

    private readonly IDBManager _dbManager;

    public CustomService(IDBManager db) => _dbManager = db;

    public async Task<ApiResult> SaveCustomAsync(ApiData data)
    {
        if (data.Exists(PLC_Sign_Card))
        {
            return await SaveCardSwipingAsync(data);
        }

        if (data.Exists(PLC_Sign_SpotCheck))
        {
            return SaveSpotCheck(data);
        }

        return ApiResult.Ok();
    }

    // 刷卡
    private async Task<ApiResult> SaveCardSwipingAsync(ApiData data)
    {
        try
        {
            var cardNo = data.GetValue<string>("PLC_Card_CardNo");

            CardSwiping item = new()
            {
                Station = data.Schema.Station,
                CardNo = cardNo,
                CreatedAt = DateTime.Now,
            };

            using var db = _dbManager.Create();
            await db.InsertAsync(item);

            return ApiResult.Ok();
        }
        catch (Exception ex)
        {
            return ApiResult.Error(ex.Message);
        }
    }

    // 点检
    private ApiResult SaveSpotCheck(ApiData data)
    {
        try
        {
            List<SpotCheck> items = new(data.Values.Length);
            foreach (var v in data.Values)
            {
                items.Add(new SpotCheck
                {
                    Station = data.Schema.Station,
                    Item = v.Name,
                    Value = v.GetValue<string>(),
                    IsPass = v.GetValue<int>() == 1,
                    CreatedAt = DateTime.Now,
                });
            }

            using var db = _dbManager.Create();
            db.InsertBatch(items);

            return ApiResult.Ok();
        }
        catch (Exception ex)
        {
            return ApiResult.Error(ex.Message);
        }
    }
}
